﻿using HardcoreGame.Common.Entities;
using HardcoreGame.Common.Systems;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.GameContent.UI.Elements;
using Terraria.Localization;
using Terraria.UI;

namespace HardcoreGame.Common.UI
{
    internal class UIItemSlot : UIElement
    {
        public UIItemSlot()
        {
            Width.Set(55f, 0f);
            Height.Set(55f, 0f);
        }
        public void Bind(Item[] arr, int index)
        {
            items = arr;
            idx = index;
        }
        public override void Draw(SpriteBatch sb)
        {
            if (items != null)
            {
                ref Item itm = ref items[idx];
                ItemSlot.Draw(sb, ref itm, 4, GetDimensions().Position(), default);
            }
        }
        public override void LeftClick(UIMouseEvent evt)
        {
            if (items != null)
            {
                ref Item slot = ref items[idx];
                ref Item cursor = ref Main.mouseItem;
                if (cursor.IsAir || BookcaseEntity.IsBook(cursor))
                {
                    Utils.Swap(ref slot, ref cursor);
                }
            }
        }
        private Item[] items;
        private int idx;
    }
    internal class BookcaseUIState : UIState
    {
        private UIText bookcaseName;
        private UIPanel panel;
        private UIItemSlot[] slots;
        private BookcaseEntity entity;
        public override void OnInitialize()
        {
            panel = new UIPanel
            {
                HAlign = 0.5f,
                VAlign = 0.5f
            };
            panel.SetPadding(5f);
            panel.Width.Set(262f, 0f);
            panel.Height.Set(182f, 0f);
            Append(panel);
            slots = new UIItemSlot[15];
            for (int i = 0; i < slots.Length; i++)
            {
                int x = i % 5;
                int y = i / 5;
                UIItemSlot slot = new();
                slot.Left.Set(x * 55, 0f);
                slot.Top.Set(y * 55 + 30f, 0f);
                panel.Append(slot);
                slots[i] = slot;
            }
            bookcaseName = new UIText("书架", 0.9f)
            {
                HAlign = 0.5f
            };
            bookcaseName.Top.Set(10f, 0f);
            panel.Append(bookcaseName);
        }
        public void SetCurrentEntity(BookcaseEntity ent)
        {
            entity = ent;
            bookcaseName.SetText(Language.GetTextValue("Mods.HardcoreGame.UI.1"));
            for (int i = 0; i < slots.Length; i++)
            {
                slots[i].Bind(ent.Items, i);
            }
        }
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            if (entity == null)
            {
                BookcaseUISystem.BookcaseInterface.SetState(null);
            }
        }
    }
}